#!/usr/bin/env python

"""
Submits the case to the queuing system, or runs it if there is no queueing system.

Also submits any other jobs (such as the short-term archiver) associated with this case.

Running case.submit is the only way you should start a job.

Typical usage is simply:
   ./case.submit

Other examples:
   ./case.submit -m begin,end
      Submits the case, requesting mail at job beginning and end
"""

from standard_script_setup import *
from CIME.case        import Case
from CIME.utils        import expect
from six.moves import configparser

###############################################################################
def parse_command_line(args, description):
###############################################################################
    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawTextHelpFormatter)

    CIME.utils.setup_standard_logging_options(parser)

    parser.add_argument("caseroot", nargs="?", default=os.getcwd(),
                        help="Case directory to submit.\n"
                        "Default is current directory.")

    parser.add_argument("--job", "-j",
                        help="Name of the job to be submitted;\n"
                        "can be any of the jobs listed in env_batch.xml.\n"
                        "This will be the first job of any defined workflow.  "
                        "Default is case.run.")

    parser.add_argument("--only-job",
                        help="Name of the job to be submitted;\n"
                        "can be any of the jobs listed in env_batch.xml.\n"
                        "Only this job will be run, workflow and RESUBMIT are ignored.  "
                        "Default is case.run.")

    parser.add_argument("--no-batch", action="store_true",
                        help="Do not submit jobs to batch system, run locally.")

    parser.add_argument("--prereq",
                        help="Specify a prerequisite job id, this job will not start until the\n"
                        "job with this id is completed (batch mode only).")

    parser.add_argument("--prereq-allow-failure", action="store_true",
                        help="Allows starting the run even if the prerequisite fails.\n"
                        "This also allows resubmits to run if the original failed and the\n"
                        "resubmit was submitted to the queue with the orginal as a dependency,\n"
                        "as in the case of --resubmit-immediate.")

    parser.add_argument("--resubmit", action="store_true",
                        help="Used with tests only, to continue rather than restart a test.")

    parser.add_argument("--resubmit-immediate", action="store_true",
                        help="This queues all of the resubmissions immediately after\n"
                        "the first job is queued. These rely on the queue system to\n"
                        "handle dependencies.")

    parser.add_argument("--skip-preview-namelist", action="store_true",
                        help="Skip calling preview-namelist during case.run.")

    CIME.utils.add_mail_type_args(parser)

    parser.add_argument("-a", "--batch-args",
                        help="Used to pass additional arguments to batch system.")

    args = CIME.utils.parse_args_and_handle_standard_logging_options(args, parser)

    CIME.utils.resolve_mail_type_args(args)

    expect(args.job is None or args.only_job is None, "Cannot specify both --job and --only-job")
    job = None
    workflow = True
    if args.job:
        job = args.job
    elif args.only_job:
        job = args.only_job
        workflow = False


    return (args.caseroot, job, args.no_batch, args.prereq, args.prereq_allow_failure,
            args.resubmit, args.resubmit_immediate, args.skip_preview_namelist, args.mail_user,
            args.mail_type, args.batch_args, workflow)

###############################################################################
def _main_func(description, test_args=False):
###############################################################################
    caseroot, job, no_batch, prereq, allow_fail, resubmit, resubmit_immediate, skip_pnl, \
        mail_user, mail_type, batch_args, workflow = parse_command_line(sys.argv, description)

    # save these options to a hidden file for use during resubmit
    config_file = os.path.join(caseroot,".submit_options")
    if skip_pnl or mail_user or mail_type or batch_args:
        config = configparser.RawConfigParser()
        config.add_section("SubmitOptions")
        if skip_pnl:
            config.set("SubmitOptions", "skip_pnl", "True")
        if mail_user:
            config.set("SubmitOptions", "mail_user", mail_user)
        if mail_type:
            config.set("SubmitOptions", "mail_type", ",".join(mail_type))
        if batch_args:
            config.set("SubmitOptions", "batch_args", batch_args)
        with open(config_file, "w") as fd:
            config.write(fd)
    elif os.path.exists(config_file):
        os.remove(config_file)

    if not test_args:
        with Case(caseroot, read_only=False) as case:
            case.submit(job=job, no_batch=no_batch, prereq=prereq, allow_fail=allow_fail,
                        resubmit=resubmit, resubmit_immediate=resubmit_immediate, skip_pnl=skip_pnl,
                        mail_user=mail_user, mail_type=mail_type, batch_args=batch_args, workflow=workflow)

if __name__ == "__main__":
    _main_func(__doc__)
